<?php 
/**
* @orm tableName forum_threads
*/
class ForumThread extends DomArObject {
	
	/**
	* @orm text
	*/
	public $name;
	/**
	* @orm text
	*/
	public $description;
	/**
	* @orm longtext
	*/
	public $longDescription;
	

	/**
	* @orm owns many ForumTopic inverse thread validateTopic()
	* @orm listener afterAdd afterAddPost
	*/
	public $topics;
	
	
	/**
	* @orm has child ForumTopic
	*/
	public $lastTopic;
	/**
	* @orm plugin DomArDateTime(now)
	*/
	public $lastPostDatetime;
	/**
	* @orm int(11)
	*/
	public $nrOfPosts = 0;
	
	
	
	/**
	* @orm int(11)
	*/
	public $views = 0;
	
	
	
	/**
	* @orm has parent ForumThread inverse threads
	*/
	public $thread;
	/**
	* @orm owns many ForumThread inverse thread
	*/
	public $threads;
	
	
	
	/**
	 * @orm bool
	 */
	public $allowTopics = true;

	/**
	 * @orm bool
	 */
	public $allowImages = true;
	
	
	
	
	public function getValidationErrorMessages() {
		return array(
			'topics' => array(
				1000 => 'Postide lisamine antud teemasse ei ole lubatud!',
			),
		);
	}
	
	/**
	* @return int [0 on success, 1000 - thread is closed]
	*/
	public function validateTopic( ForumTopic $topic ) {
		if( $this->allowTopics === true )
			return 0;
			
		return 1000;
	}
	
	public function afterAddPost( ForumPostBase $post ) {
		
		if( $post instanceof ForumPost )
			$this->lastTopic = $post->topic;
		else
			$this->lastTopic = $post;
			
		$this->lastPostDatetime = $post->datetime->datetime();
		$this->nrOfPosts++;
		if( $this->thread )
			$this->thread->afterAddTopic( $post );
	}
	
	public function beforeDeletePost( ForumPostBase $post ) {
		if( $post instanceof ForumPost )
			$this->nrOfPosts--;
		else
			$this->nrOfPosts -= 1+$post->posts->count();
			
		if( $this->thread )
			$this->thread->beforeDeletePost( $post );
		
		$this->save();
	}
	
	
	
	public static function getTree( $addNo = false, $parentId = 0, $level = 0, &$list = array() ) {
		
		//if( self::$treeCache !== NULL )
		//	return self::$treeCache;
		
		if( $addNo == true )
			$list[0] = array('value' =>$addNo, 'id'=>0, 'level' => 0);
		
		$categories = self::query()->where('thread'.($parentId == 0 ? ' <=> NULL' : '='.(int)$parentId))->commit();
		foreach( $categories as $category ) {
			$list[$category->id] = array('value' => $category->name, 'id' => $category->id, 'level' => $level );
			self::getTree( false, $category->id, $level+1, $list );
		}
		
		//if( $parentId === 0 )
			//self::$treeCache = $list;
		
		return $list;
	}
	
	

}
?>